cap program drop labelfromstring
program labelfromstring, rclass
syntax, stringvar(string) numvar(string) 

tempvar counter
tempname dt labeldo
frame copy default `dt'
frame `dt' {

	* reduce 
	quiet bysort `stringvar' `numvar': keep if _n==1
	keep `stringvar' `numvar'

	* check mapping 
	bysort `numvar': g `counter' = _N
	qui su `counter'
	loc N = r(max)
	if (`N' > 1) {
		list if `counter' > 1
		di as err "no unique mapping between `stringvar' and `numvar'!"
		exit 
	}

	* Drop quotation marks in stringvar
	qui replace `stringvar' = subinstr(`stringvar', char(34), "", .)

	* Define a Label
	forv r = 1/`c(N)' {
		loc val = `numvar'[`r']
		loc lab = `stringvar'[`r']
		if (!mi(`val')==1) la def `numvar' `val' "`lab'", add
	}

	* temp save labels
	qui label save `numvar' using "`labeldo'.do", replace

}

* apply label
run "`labeldo'.do"
label values `numvar' `numvar'
numlabel `numvar', add

* drop label file
erase "`labeldo'.do"
	
end
*****
*-------------------------------------------------------------------------------
